package com.weayer.constraints;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @description: 自定义日期校验实现类
 * @author: Weayer
 **/
public class DateTimeRangeValidator implements ConstraintValidator<DateTimeRange, Object> {
    private DateTimeRange dateTimeRange;
    private String judge;

    @Override
    public void initialize(DateTimeRange constraintAnnotation) {
        judge = constraintAnnotation.judge();
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Object paramDate, ConstraintValidatorContext constraintValidatorContext) {
        if(paramDate == null){
            return true;
        }
        // 日期参数
        LocalDateTime dateValue = null;
        if(paramDate instanceof LocalDateTime){
            dateValue = (LocalDateTime) paramDate;
        }
        if(paramDate instanceof String){
            dateValue = LocalDateTime.parse((String)paramDate, DateTimeFormatter.ofPattern(dateTimeRange.pattern()));
        }
        LocalDateTime now = LocalDateTime.now();
        // 日期参数晚于当前时间
        if(judge.equals(DateTimeRange.IS_AFTER) && dateValue.isAfter(now)){
            return true;
        }
        // 日期参数早于当前时间
        if(judge.equals(DateTimeRange.IS_BEFORE) && dateValue.isBefore(now)){
            return true;
        }
        return false;
    }
}
